package com.freesun.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freesun.shop.domin.ProdSolr;
import com.freesun.shop.entity.Prod;
import com.freesun.shop.service.ProdService;
import com.freesun.shop.service.SearchService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {

    private static Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);

    @Reference(check = false)
    private ProdService prodService;

    @Autowired
    private SolrClient solrClient;
    @Value("${solr.import.num}")
    private Integer solrImportNum;
    @Override
    //@PostConstruct //程序一启动就运行
    public void importAllProd() {
        logger.info("开始全部导入");
        Page<Prod> page = new Page<Prod>(1, solrImportNum);
        IPage<ProdSolr> firstPageData = prodService.findProdSolrPage(null, page);
        List<ProdSolr> prodSolrList = firstPageData.getRecords();
        if (prodSolrList != null && !prodSolrList.isEmpty()) {
            import2Solor(prodSolrList);
        }
           long pages = firstPageData.getPages();
            for (int i = 1; i < pages; i++) {
                Page<Prod> pageEach = new Page<>(i, solrImportNum);
                IPage<ProdSolr> EachPageData= prodService.findProdSolrPage(null, pageEach);
                List<ProdSolr> eachProdSolrList = EachPageData.getRecords();
                import2Solor(eachProdSolrList);
            }
    }

    private void import2Solor(List<ProdSolr> prodSolrList) {
        List<SolrInputDocument> prodSolrDocs = new ArrayList<>();
        for (ProdSolr prodSolr : prodSolrList) {
            prodSolrDocs.add(prodSolr2prodSolrDoc(prodSolr));
        }
        try {
            solrClient.add(prodSolrDocs);
            solrClient.commit();
            System.out.println("导入成功！！");
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private SolrInputDocument prodSolr2prodSolrDoc(ProdSolr prodSolr) {
        SolrInputDocument document = new SolrInputDocument();
        document.addField("id",prodSolr.getId());
        document.addField("prod_name",prodSolr.getProdName());
        document.addField("pic",prodSolr.getPic());
        document.addField("praise_number",prodSolr.getPraiseNumber());
        document.addField("positive_rating",prodSolr.getPositiveRating().floatValue());
        document.addField("brief",prodSolr.getBrief());
        document.addField("price",prodSolr.getPrice().floatValue());
        document.addField("tag_list", prodSolr.getTagList());
        document.addField("category_id",prodSolr.getCategoryId());
        document.addField("sold_num",prodSolr.getSoldNum());
        return document;
    }

    @Override
    public List<ProdSolr> serachByTagId(Long tagId, Integer size) {
        Assert.notNull(tagId, "商品标签ID不能为Null");
        logger.info("本次搜索的商品标签为:{}",tagId);
        SolrQuery solrQuery = new SolrQuery("tag_list:" + tagId);
        solrQuery.setStart(0);
        solrQuery.setRows(size);
        return searchByQuery(solrQuery);
    }

    private List<ProdSolr> docs2ProdSolrList(SolrDocumentList results) {
        List<ProdSolr> prodSolrs = new ArrayList<>(results.size());
        for (SolrDocument result : results) {
            prodSolrs.add(doc2ProdSolr(result));
        }
        return prodSolrs;
    }

    private ProdSolr doc2ProdSolr(SolrDocument result) {
        ProdSolr prodSolr = new ProdSolr();
        prodSolr.setId(result.getFieldValue("id").toString());
        prodSolr.setProdName(result.getFieldValue("prod_name").toString());
        prodSolr.setPrice(new BigDecimal(result.getFieldValue("price").toString()));
        prodSolr.setPic(result.getFieldValue("pic").toString());
        prodSolr.setPraiseNumber(Long.valueOf(result.getFieldValue("praise_number").toString()));
        prodSolr.setPositiveRating(new BigDecimal(result.getFieldValue("positive_rating").toString()));
        prodSolr.setBrief(result.getFieldValue("brief").toString());
        return prodSolr;
    }

    @Override
    public List<ProdSolr> serachByCatId(Long categoryId) {
        logger.info("查询的商品ID为:{}"+categoryId);
        SolrQuery solrQuery = new SolrQuery("category_id:"+categoryId);
        return searchByQuery(solrQuery);
    }

    private List<ProdSolr> searchByQuery(SolrQuery solrQuery) {
        List<ProdSolr> prodSolrList =null;
        try {
            QueryResponse queryResponse = solrClient.query(solrQuery);
            SolrDocumentList results = queryResponse.getResults();
            prodSolrList=docs2ProdSolrList(results);
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
        return prodSolrList;
    }

    @Override
    public IPage<ProdSolr> search(Page<ProdSolr> page, String prodName, Integer sort) {
        SolrQuery solrQuery = new SolrQuery("keyword:" + prodName);
        solrQuery.setStart(Integer.valueOf(String.valueOf((page.getCurrent()-1)*page.getSize())));
        solrQuery.setRows(Integer.valueOf(String.valueOf(page.getCurrent()*page.getSize())));
        switch (sort) {
            case 0: //综合排序(好评)
                solrQuery.setSort("positive_rating", SolrQuery.ORDER.desc);
                break;
            case 1: //销量排序
                solrQuery.setSort("sold_num", SolrQuery.ORDER.desc);
                break;
            case 2: //价格排序
                solrQuery.setSort("price", SolrQuery.ORDER.asc);
                break;
                default:
                    throw new RuntimeException("不支持的排序");
        }
        List<ProdSolr> prodSolrs = searchByQuery(solrQuery);
        page.setRecords(prodSolrs);
        return page;
    }
}
